package com.project.util;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel文件添加内容工具类
 *
 * @author Leo高洋
 * @create 2023-04-08 1:31
 */
public class SpinnerWriteHandler implements SheetWriteHandler {

    private final List<String> assetTypeList;
    private final List<String> staffList;

    /**
     * 接收方法
     *
     * @param list1
     * @param lis2
     */
    public SpinnerWriteHandler(List<String> list1, List<String> lis2) {
        this.assetTypeList = list1;
        this.staffList = lis2;
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        String[] strings = ArrayUtil.toArray(assetTypeList, String.class);
        String[] strings2 = ArrayUtil.toArray(staffList, String.class);
        Map<Integer, String[]> mapDropDown = new HashMap<>();
        // 这里的数值对应导出列的顺序,从0开始,strings为下拉选框的值
        mapDropDown.put(1, strings);
        mapDropDown.put(8, strings2);
        // 获取到当前的sheet
        Sheet sheet = writeSheetHolder.getSheet();
        // 获得Workbook 工作蒲
        Workbook workbook = writeWorkbookHolder.getWorkbook();
        // 创建一个样式
        CellStyle cellStyle = workbook.createCellStyle();
        // 给样式添加自定义样式
        // Workbook创建一个时间格式 然后获得时间格式输入自己想要的时间格式
        cellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd"));
        // 设置样式给指定列
        sheet.setDefaultColumnStyle(6, cellStyle);
        sheet.setDefaultColumnStyle(7, cellStyle);
        /// 开始设置下拉框
        DataValidationHelper helper = sheet.getDataValidationHelper();// 设置下拉框
        for (Map.Entry<Integer, String[]> entry : mapDropDown.entrySet()) {
            // 起始行、终止行、起始列、终止列
            CellRangeAddressList addressList = new CellRangeAddressList(1, 1000, entry.getKey(), entry.getKey());
            // 设置下拉框数据
            DataValidationConstraint constraint = helper.createExplicitListConstraint(entry.getValue());
            DataValidation dataValidation = helper.createValidation(constraint, addressList);
            // 处理Excel兼容性问题
            if (dataValidation instanceof XSSFDataValidation) {
                dataValidation.setSuppressDropDownArrow(true);
                dataValidation.setShowErrorBox(true);
            } else {
                dataValidation.setSuppressDropDownArrow(false);
            }
            sheet.addValidationData(dataValidation);
        }
    }
}